/*
* Copyrignt (c) xuzeshui.com. All Rights Reserved.
* Author: Xiaobao Zeng<zengxiaobao@skyworth.com>
* Created Time: 2016-09-20 18:13:15
 * Last Modified: 2017-03-28 14:09:22
* File Name: advertoper_admin.go
* Description:
*/

package adoper

import (
	//"encoding/json"
	"strings"
	//"time"

	"advertoper/db"
	"advertoper/errorcode"

	"doubimeizhi.com/datatable"

	log "github.com/cihub/seelog"
)

var (
	defaultAdvertoperAdminService *AdvertoperAdminService
)

type AdvertoperAdminService struct {
}

func newAdvertoperAdminService() *AdvertoperAdminService {
	service := &AdvertoperAdminService{}
	return service
}
func GetAdvertoperAdminService() *AdvertoperAdminService {
	if defaultAdvertoperAdminService == nil {
		defaultAdvertoperAdminService = newAdvertoperAdminService()
	}
	return defaultAdvertoperAdminService
}

//查看商品列表
type ShowItemReq struct {
	PageIndex int  //分页页码
	PageSize  int  //分页的大小
	Role      bool //访问角色，客户端true, 后台false
}

//元素布局信息
type LayoutInfo struct {
	Appkey       string `json:"appkey"`
	Plat         string `json:"plat"`
	Position     int    `json:"position"`
	PositionDesc string `json:"position_desc"`
	Layout       string `json:"layout"`
	InsertTick   int64  `json:"insert_tick"`
	UpdateTick   int64  `json:"update_tick"`
	Status       int    `json:"status"`
}

type ShowItemResp struct {
	Code      uint
	Msg       string
	Layout    string `json:"layout"`
	Data      []interface{}
	HasMore   bool
	Total     int
	PageIndex int
	PageSize  int //分页的大小
}

//查看所有的广告位元素
func (p *AdvertoperAdminService) ShowLayouts(req *ShowItemReq, resp *ShowItemResp) error {
	if req.PageSize == 0 {
		resp.PageSize = 10
	}
	dtq := datatable.NewDataTableQuery()
	dtq.SetTableName("advert_layout")
	dtq.SetPage(req.PageIndex*req.PageSize, req.PageSize)
	dtq.PushField(&datatable.FiledItem{Alias: "appkey", Field: "appkey"})
	dtq.PushField(&datatable.FiledItem{Alias: "plat", Field: "plat"})
	dtq.PushField(&datatable.FiledItem{Alias: "position", Field: "position"})
	dtq.PushField(&datatable.FiledItem{Alias: "position_desc", Field: "position_desc"})
	dtq.PushField(&datatable.FiledItem{Alias: "layout", Field: "layout"})
	dtq.PushField(&datatable.FiledItem{Alias: "insert_tick", Field: "insert_tick"})
	dtq.PushField(&datatable.FiledItem{Alias: "update_tick", Field: "update_tick"})
	dtq.PushField(&datatable.FiledItem{Alias: "status", Field: "status"})

	sql, values := dtq.GenerateSQL()
	mysqlHelper := db.GetMysqlHelper()
	if results, err := mysqlHelper.Query(sql, values...); err == nil {
		resp.Data = make([]interface{}, 0, len(results))
		for _, dt := range results {
			info := &LayoutInfo{}
			info.Appkey = mysqlHelper.GetColString(dt, "appkey")
			info.Plat = mysqlHelper.GetColString(dt, "plat")
			info.Position = mysqlHelper.GetColInt(dt, "position")
			info.PositionDesc = mysqlHelper.GetColString(dt, "position_desc")
			info.Layout = mysqlHelper.GetColString(dt, "layout")
			info.InsertTick = mysqlHelper.GetColInt64(dt, "insert_tick")
			info.UpdateTick = mysqlHelper.GetColInt64(dt, "update_tick")
			info.Status = mysqlHelper.GetColInt(dt, "status")
			resp.Data = append(resp.Data, info)
		}
	} else {
		log.Warnf("mysql error sql: %s, values: %v", err.Error(), values)
	}
	if !req.Role {
		s, v := dtq.GenerateTotalRecordSQL("total_records")
		if results, err := mysqlHelper.Query(s, v...); err == nil {
			if len(results) > 0 {
				resp.Total = mysqlHelper.GetColInt(results[0], "total_records")
			}
		} else {
			log.Warnf("mysql error sql: %s, values: %v", err.Error(), values)
		}
	}
	if resp.Total > req.PageSize {
		resp.HasMore = true
	}
	resp.Code = errorcode.EC_GL_SUCCESS
	resp.Msg = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	resp.PageIndex = req.PageIndex

	return nil
}

type PositionDataReq struct {
	ShowItemReq
	Start  int    `json:"start"`
	Length int    `json:"length"`
	Appkey string `json:"appkey"`
	Ids    string `json:"ids"`
	Action int    `json:"action"`
	//	TimeRange int    `json:"time_range"`
	//	Status    int    `json:"status"`
}

//特定app特定位置元素信息
type PositionDataInfo struct {
	Id          int64  `json:"id"`         //id
	Type        int    `json:"type"`       //类型
	StartTick   int64  `json:"start_tick"` //开始时间
	EndTick     int64  `json:"end_tick"`
	Weight      int    `json:"weight"`
	VersionCode string `json:"versioncode"`
	Region      string `json:"region"`
	Channel     string `json:"channel"`
	Clickable   int    `json:"clickable"`
	Action      int    `json:"action"`
	Args        string `json:"args"`
	Router      string `json:"router"`
	Content     string `json:"params"`
	InsertTick  int64  `json:"insert_tick"`
	UpdateTick  int64  `json:"update_tick"`
	Status      int    `json:"status"`
}

//查看特定app特定位置的元素信息
func (p *AdvertoperAdminService) ShowPositionData(req *PositionDataReq, resp *ShowItemResp) error {
	if req.PageSize == 0 {
		resp.PageSize = 10
	}
	dtq := datatable.NewDataTableQuery()
	dtq.SetTableName("advert_oper_redesign")
	dtq.SetPage(req.Start, req.Length)
	dtq.PushField(&datatable.FiledItem{Alias: "id", Field: "id", OrderBy: datatable.DESC})
	dtq.PushField(&datatable.FiledItem{Alias: "type", Field: "type"})
	dtq.PushField(&datatable.FiledItem{Alias: "start_tick", Field: "start_tick"})
	dtq.PushField(&datatable.FiledItem{Alias: "end_tick", Field: "end_tick"})
	dtq.PushField(&datatable.FiledItem{Alias: "weight", Field: "weight"})
	dtq.PushField(&datatable.FiledItem{Alias: "version_code", Field: "version_code"})
	dtq.PushField(&datatable.FiledItem{Alias: "region", Field: "region"})
	dtq.PushField(&datatable.FiledItem{Alias: "channel", Field: "channel"})
	dtq.PushField(&datatable.FiledItem{Alias: "clickable", Field: "clickable"})
	dtq.PushField(&datatable.FiledItem{Alias: "router", Field: "router"})
	dtq.PushField(&datatable.FiledItem{Alias: "pic", Field: "pic"})
	dtq.PushField(&datatable.FiledItem{Alias: "web_url", Field: "web_url"})
	dtq.PushField(&datatable.FiledItem{Alias: "content", Field: "content"})
	dtq.PushField(&datatable.FiledItem{Alias: "insert_tick", Field: "insert_tick"})
	dtq.PushField(&datatable.FiledItem{Alias: "update_tick", Field: "update_tick"})
	dtq.PushField(&datatable.FiledItem{Alias: "status", Field: "status"})

	if req.Action == 1 {
		idArrays := strings.Split(req.Ids, ",")
		dtq.PushCondition("id in ?", idArrays)
	}

	sql, values := dtq.GenerateSQL()
	mysqlHelper := db.GetMysqlHelper()
	if results, err := mysqlHelper.Query(sql, values...); err == nil {
		resp.Data = make([]interface{}, 0, len(results))
		for _, dt := range results {
			item := &PositionDataInfo{}
			item.Id = mysqlHelper.GetColInt64(dt, "id")
			item.Type = mysqlHelper.GetColInt(dt, "type")
			item.StartTick = mysqlHelper.GetColInt64(dt, "start_tick")
			item.EndTick = mysqlHelper.GetColInt64(dt, "end_tick")
			item.Weight = mysqlHelper.GetColInt(dt, "weight")
			item.VersionCode = mysqlHelper.GetColString(dt, "version_code")
			item.Region = mysqlHelper.GetColString(dt, "region")
			item.Channel = mysqlHelper.GetColString(dt, "channel")

			item.Clickable = mysqlHelper.GetColInt(dt, "clickable")

			item.Router = mysqlHelper.GetColString(dt, "router")
			item.InsertTick = mysqlHelper.GetColInt64(dt, "insert_tick")
			item.UpdateTick = mysqlHelper.GetColInt64(dt, "update_tick")
			item.Status = mysqlHelper.GetColInt(dt, "status")
			//类型是图片，content是图片的(size,url)信息，json格式
			//-----------------------------获取图片的下载连接----------------------------//
			if item.Type == 2 {
				temp := mysqlHelper.GetColString(dt, "pic")
				//	log.Debugf(temp)
				temp = strings.TrimSuffix(temp, "]")
				temp = strings.TrimPrefix(temp, "[")
				temp = strings.Replace(temp, `},{`, `}###$$$###{`, -1)
				//log.Debugf(temp)
				item.Content = temp
			} else if item.Type == 3 {
				item.Content = mysqlHelper.GetColString(dt, "web_url")
			} else {
				item.Content = mysqlHelper.GetColString(dt, "content")
			}

			resp.Data = append(resp.Data, item)
		}
	} else {
		resp.Data = make([]interface{}, 0, 0)
		log.Warnf("mysql error sql: %s, values: %v", err.Error(), values)
	}
	if !req.Role {
		s, v := dtq.GenerateTotalRecordSQL("total_records")
		if results, err := mysqlHelper.Query(s, v...); err == nil {
			if len(results) > 0 {
				resp.Total = mysqlHelper.GetColInt(results[0], "total_records")
			}
		} else {
			log.Warnf("mysql error sql: %s, values: %v", err.Error(), values)
		}
	}
	if resp.Total > req.PageSize {
		resp.HasMore = true
	}
	resp.Code = errorcode.EC_GL_SUCCESS
	resp.Msg = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	resp.PageIndex = req.PageIndex
	return nil
}

func (p *AdvertoperAdminService) DeleteAdvertItem(appkey string, position, id, action int) uint {
	dtd := datatable.NewDataTableDelete()
	table := ""
	if action == 1 {
		table = "advert_layout"
		dtd.SetTableName("advert_layout")
		dtd.PushCondition("appkey=?", appkey)
		dtd.PushCondition("position=?", position)
	} else {
		table = "advert_oper_redesign"
		dtd.SetTableName("advert_oper_redesign")
		dtd.PushCondition("id=?", id)
	}
	sql, values := dtd.GenerateSQL()
	mysqlHelper := db.GetMysqlHelper()
	if _, err := mysqlHelper.Exec(sql, values...); err != nil {
		log.Warnf("DeleteAdvertInfo, mysql error, error:%s, table: %s, appkey:%s, position:%d, id%d", err.Error(), table, appkey, position, id)
		return errorcode.EC_GL_INTERNAL_ERROR
	}
	log.Debug("DeleteAdvertInfo.......", id)
	return errorcode.EC_GL_SUCCESS

}
